/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
*/

package com.jinhe.tss.core.util;

/**
 * <p> XmlUtil.java </p>
 * <p>
 * XML相关工具类
 * </p>
 */
public class XmlUtil {
    
    /**
     * 剔除XML文件中不合法的字符，像 "" 这种字符存在会导致: <br>
     * org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0xb) was found in the element content of the document. <br>
     * 这样的异常出现，而用IE预览XML时却完全正常。<br>
     * 
     * @param in
     * @return
     */
    public static String stripNonValidXMLCharacters(String in) {
        if ( EasyUtils.isNullOrEmpty(in) ) return ""; // vacancy test.
        
        StringBuffer out = new StringBuffer(); // Used to hold the output.
        char current; // Used to reference the current character.
        for (int i = 0; i < in.length(); i++) {
            current = in.charAt(i); 
            if ((current == 0x9) ||(current == 0xA) || (current == 0xD) ||
                ((current >= 0x20) && (current <= 0xD7FF)) ||
                ((current >= 0xE000) && (current <= 0xFFFD)) ||
                ((current >= 0x10000) && (current <= 0x10FFFF)))
                out.append(current);
        }
        return out.toString();
    }
    
//    public class StripNonValidXMLCharactersInputStream extends FilterInputStream {
//
//        /**
//         * 构造函数
//         * @param in
//         */
//        public StripNonValidXMLCharactersInputStream(InputStream in) {
//            super(in);
//        }
//
//        /**
//         * <p>
//         * 读取下一个字节
//         * </p>
//         * @return
//         * @throws IOException
//         * @see java.io.FilterInputStream#read()
//         */
//        public int read() throws IOException {
//            while (true) {
//                int read = in.read();
//                char current = (char) read;
//                if ((current == 0x9) || (current == 0xA) || (current == 0xD)
//                        || ((current >= 0x20) && (current <= 0xD7FF))
//                        || ((current >= 0xE000) && (current <= 0xFFFD))
//                        || ((current >= 0x10000) && (current <= 0x10FFFF))
//                        || (read == -1)) {
//                    return read;
//                }
//            }
//        }
//
//        /**
//         * <p>
//         * 读取特定（给定数组长度或结束）长度数据存放到给定数组中
//         * </p>
//         * @param b 给定字节数组
//         * @return 返回读取长度
//         * @throws IOException
//         * @see java.io.FilterInputStream#read(byte[])
//         */
//        public int read(byte b[]) throws IOException {
//            return read(b, 0, b.length);
//        }
//
//        /**
//         * <p>
//         * 读取指定位置开始，指定长度或结束为止的字节数据，存放到给定的数据中
//         * </p>
//         * @param b
//         *            给定数组
//         * @param off
//         *            指定其实位置
//         * @param len
//         *            指定长度
//         * @return
//         * @throws IOException
//         * @see java.io.FilterInputStream#read(byte[], int, int)
//         */
//        public int read(byte b[], int off, int len) throws IOException {
//            if (b == null) {
//                throw new NullPointerException();
//            } else if ((off < 0) || (off > b.length) || (len < 0)
//                    || ((off + len) > b.length) || ((off + len) < 0)) {
//                throw new IndexOutOfBoundsException();
//            } else if (len == 0) {
//                return 0;
//            }
//
//            int c = read();
//            if (c == -1) {
//                return -1;
//            }
//            b[off] = (byte) c;
//
//            int i = 1;
//            try {
//                for (; i < len; i++) {
//                    c = read();
//                    if (c == -1) {
//                        break;
//                    }
//                    if (b != null) {
//                        b[off + i] = (byte) c;
//                    }
//                }
//            } catch (IOException ee) {
//            }
//            return i;
//        }
//
//        public static void main(String[] args) throws DocumentException, IOException {
//            FileInputStream is = new FileInputStream(URLUtil.getResourceFileUrl("appServers.xml").getPath());
//            StripNonValidXMLCharactersInputStream xis = new StripNonValidXMLCharactersInputStream(is);
//            
//            int bytesRead = 0;
//            OutputStream out = new ByteArrayOutputStream();
//            final int length = 8192;
//            byte[] buffer = new byte[length];
//            while ((bytesRead = xis.read(buffer, 0, length)) != -1) {
//                out.write(buffer, 0, bytesRead);
//                out.flush();
//            }
//            System.out.print(out.toString());
//        }
//    }

    /**
     * 将一个对象转换成xml支持的格式，包括特殊字符、null显示成""以及数字等于0时显示成""
     * 
     * @param obj
     * @return
     */
    public static String toFormXml(Object obj) {
        if (obj == null) {
            return "";
        }
        String message = obj.toString();
        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
            case '<':
                result.append("&lt;");
                break;
            case '>':
                result.append("&gt;");
                break;
            case '&':
                result.append("&amp;");
                break;
            case '"':
                result.append("&quot;");
                break;
            default:
                result.append(content[i]);
            }
        }
        return (result.toString());
    }
    
    /**
     * 替换XML数据属性值中的特殊字符，包括<、>、"、&等
     * 
     * @param string
     * @return
     */
    public static String replaceXMLPropertyValue(String xmlStr) {
        return xmlStr.replaceAll("&", "&amp;")
                     .replaceAll("\"", "&quot;")
                     .replaceAll("<", "&lt;")
                     .replaceAll(">", "&gt;");
    }
}

